package com.jsgt.greekfire.ui.mine.user

import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import com.fhx.core.base.BaseActivity
import com.fhx.core.goToActivity
import com.fhx.core.utils.*
import com.jsgt.greekfire.*
import com.jsgt.greekfire.bean.AssetsBean
import com.jsgt.greekfire.bean.UserBean
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.event.USDTPriceEvent
import com.jsgt.greekfire.ui.mine.adapter.AssetsAdapter
import com.jsgt.greekfire.ui.mine.assetsmanage.AssetsManageActivity
import com.jsgt.greekfire.ui.mine.coindetail.CoinDetailActivity
import com.jsgt.greekfire.ui.mine.coindetail.recharge.RechargeActivity
import com.jsgt.greekfire.ui.mine.coindetail.withdraw.WithdrawActivity
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.fragment_assets.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 我的
 * author fhx
 * create time 2020/4/22 20:51
 **/
class UserActivity : BaseActivity(), View.OnClickListener {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }


    private var actionWindow: PopupWindow? = null
    private var totalBalance = 0.0
    override fun getLayoutId(): Int = R.layout.fragment_assets
    var assetsAdapter: AssetsAdapter? = null
    override fun onResume() {
        super.onResume()
        loadData()
    }

//    override fun onHiddenChanged(hidden: Boolean) {
//        super.onHiddenChanged(hidden)
//        if (!hidden) {
//            loadData()
//        }
//    }

    override fun main() {
        setTopPadding(assets_header_view)

        textView19.setOnClickListener {

            goToActivity<UserActivity>()
        }

        val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        decoration.setDrawable(resources.getDrawable(R.drawable.divider_main_assets))
        assets_rv.addItemDecoration(decoration)
        assetsAdapter = AssetsAdapter()

        //数字币详情
        assetsAdapter!!.itemClickListner = {
            CoinDetailActivity.start(this, it)
        }
        assets_rv.adapter = assetsAdapter
        val actionView = layoutInflater.inflate(R.layout.view_assets_action_window, null, false)
        actionView.findViewById<TextView>(R.id.recharge_tv).setOnClickListener(this)
        actionView.findViewById<TextView>(R.id.withdraw_tv).setOnClickListener(this)
        actionView.findViewById<TextView>(R.id.assets_manage_tv).setOnClickListener(this)

        actionWindow = PopupWindow(
            actionView,
            ScreenUtil.dip2px(this, 175f).toInt(),
            ScreenUtil.dip2px(this, 162f).toInt()
        )
        //actionWindow?.isOutsideTouchable = true
        actionWindow?.isFocusable = true
        actionWindow?.setBackgroundDrawable(BitmapDrawable())//这行代码是必须的
        action_iv.setOnClickListener {
            if (actionWindow!!.isShowing) {
                actionWindow!!.dismiss()
            } else {
                actionWindow!!.showAsDropDown(
                    action_iv, -ScreenUtil.dip2px(this, 145f).toInt(),
                    ScreenUtil.dip2px(this, 17f).toInt()
                )
            }
        }
        refresh_layout.setOnRefreshListener {
            loadData()
        }
        loadData()

        userViewModel.userInfoLiveData.observe(this, Observer {
            UserBean.instance.mobile = it.mobile
            UserBean.instance.email = it.email
        })
        userViewModel.errorLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
        })
        balance_view_tv.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                total_assets_tv.text = "******"
                rmb_mark_tv.visibility = View.INVISIBLE
                SharePreferencesUtil.saveBoolean(this, SUM_IS_VIEW, true)
            } else {
                total_assets_tv.text = PriceFormatUtil.format(totalBalance, 4)
                rmb_mark_tv.visibility = View.VISIBLE
                SharePreferencesUtil.saveBoolean(this, SUM_IS_VIEW, false)
            }
        }
    }

    fun loadData() {
        if (LOGIN_STATUS) {
            NetDataManager.getUSTDPrice()
            NetDataManager.getUserAssets()
            userViewModel.userInfo()
        }
    }
    override fun onClick(v: View?) {
        actionWindow?.dismiss()

        when (v!!.id) {
            //充值
            R.id.recharge_tv -> {
                startActivity(Intent(this, RechargeActivity::class.java))
            }
            //提币
            R.id.withdraw_tv -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(this, getString(R.string.account_no_activation))
                } else {
                    startActivity(Intent(this, WithdrawActivity::class.java))
                }
            }
            //资产管理
            R.id.assets_manage_tv -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(this, getString(R.string.account_no_activation))
                } else {
                    startActivity(
                        Intent(
                            this,
                            AssetsManageActivity::class.java
                        )
                    )
                }
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTransferEvent(e: TransferEvent) {
        loadData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
        refresh_layout.isRefreshing = false
        totalBalance = NetDataManager.getCountAsset()

        if (SharePreferencesUtil.getBoolean(this, SUM_IS_VIEW, false)) {
            total_assets_tv.text = "******"
            rmb_mark_tv.visibility = View.INVISIBLE
            balance_view_tv.isChecked = true
        } else {
            total_assets_tv.text = PriceFormatUtil.format(totalBalance, 4)
            rmb_mark_tv.visibility = View.VISIBLE
            balance_view_tv.isChecked = false
        }
        assetsAdapter?.refreshData(filterList(NetDataManager.assetsList))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUSDTPriceEvent(e: USDTPriceEvent) {
        assetsAdapter?.refreshData(filterList(NetDataManager.assetsList))
    }

    private fun filterList(list: List<AssetsBean>): List<AssetsBean> = list.filter {
        it.assetGuid!!.toInt() < 5
    }

    override fun onDestroy() {
        super.onDestroy()
        actionWindow = null
    }


//    // 定义保存的文件的名称
//    private val languageName = "sharedfile"
//
//
//    private val userViewModel: UserViewModel by lazy {
//        ViewModelProvider(
//            this,
//            UserViewModelFactory()
//        ).get(UserViewModel::class.java)
//    }
//    private val walletViewModel: WalletViewModel by lazy {
//        ViewModelProvider(
//            this,
//            WalletViewModelFactory()
//        ).get(WalletViewModel::class.java)
//    }
//    private var pwdDialog: Dialog? = null
//
//    companion object {
//        const val REQUEST_CODE = 1011
//    }
//
//    override fun getLayoutId(): Int = R.layout.fragment_mine
//
//    override fun onResume() {
//        super.onResume()
//        userViewModel.userInfo()
//    }
//
//    override fun main() {
//        title = getString(R.string.mine)
//        exit_tv.setOnClickListener(this)
//        activities_confirm_tv.setOnClickListener(this)
//        msg_center_ll.setOnClickListener(this)
//        address_book_ll.setOnClickListener(this)
//        money_type_ll.setOnClickListener(this)
//        market_option_ll.setOnClickListener(this)
//        user_language_ll.setOnClickListener(this)
//        change_trading_pwd_ll.setOnClickListener(this)
//        change_security_pwd_ll.setOnClickListener(this)
//        security_set_ll.setOnClickListener(this)
//        recommend_download_ll.setOnClickListener(this)
//        user_change_wallet_ll.setOnClickListener(this)
//        backup_wallet_ll.setOnClickListener(this)
//        copy_tv.setOnClickListener(this)
//        userViewModel.activityTransferList()
//
//
//        userViewModel.activityTransferList.observe(this, Observer {
//            if (IS_ACTIVATION == 1) {
//                if (it != null && it.isNotEmpty()) {
//                    transfer_record_tv.text = "ID:${it[0].fromUserName}给你转了${it[0].amount}GLB"
//                    activity_transfer_ll.visibility = View.VISIBLE
//                }
//            } else {
//                activity_transfer_ll.visibility = View.GONE
//            }
//        })
//        showProgress(true)
//        NetDataManager.getWalletInfo()
//        userViewModel.userInfoLiveData.observe(this, Observer {
//            UserBean.instance.mobile = it.mobile
//            UserBean.instance.email = it.email
//        })
//
//        //备份钱包的判断
//        walletViewModel.checkSecurityLiveData.observe(this, Observer {
//            //showToast("密码验证成功")
//            showProgress(false)
//            pwdDialog?.dismiss()
//            pwdDialog = null
//            BackUpWalletWordActivity.start(this)
//        })
//        walletViewModel.errorLiveData.observe(this, Observer {
//            showProgress(false)
//        })
//        userViewModel.errorLiveData.observe(this, Observer {
//            showProgress(false)
//        })
//
//
//        when (SharePreferencesUtil.getString(this, languageName, "")) {
//
//            "cn" -> {
//                simplified_chinese.text =getString(R.string.Simplified_Chinese)
//            }
//            "en" -> {
//                simplified_chinese.text ="English"
//
//            }
//        }
//
//    }
//
//    override fun onClick(v: View?) {
//        when (v?.id) {
//            R.id.exit_tv -> exit()
//            //激活列表
//            R.id.activities_confirm_tv -> {
//                startActivityForResult(
//                    Intent(this, ActivationListActivity::class.java),
//                    REQUEST_CODE
//                )
//            }
//            //通知列表
//            R.id.msg_center_ll -> startActivity(Intent(this, MessageListActivity::class.java))
//            //地址簿
//            R.id.address_book_ll -> {
//                AddressActivity.start(
//                    this,
//                    AddressActivity.USER
//                )
//            }
//            //计价货币
//            R.id.money_type_ll -> startActivity(Intent(this, MoneyTypeActivity::class.java))
//            //行情选项
//            R.id.market_option_ll -> startActivity(Intent(this, MarketOptionActivity::class.java))
//            //显示语言
//            R.id.user_language_ll -> startActivity(Intent(this, LanguageActivity::class.java))
//            //修改交易密码
//            R.id.change_trading_pwd_ll -> {
//                if (IS_ACTIVATION == 1) {
//                    ToastUtils.show(this, getString(R.string.account_no_activation))
//                } else {
//                    if (TextUtils.isEmpty(UserBean.instance.mobile)) {
//                        ToastUtils.show(this, "请先绑定手机")
//                    } else {
//                        startActivity(Intent(this, ChangeTradingPwdActivity::class.java))
//                    }
//                }
//            }
//            // 创建/导入钱包
//            R.id.user_change_wallet_ll -> {
//                EntranceActivity.start(this)
//            }
//            //修改安全密码
//            R.id.change_security_pwd_ll -> {
//                if (IS_ACTIVATION == 1) {
//                    ToastUtils.show(this, getString(R.string.account_no_activation))
//                } else {
//                    startActivity(Intent(this, ChangeSecurityPwdActivity::class.java))
//                }
//            }
//            //安全设置
//            R.id.security_set_ll -> {
//                if (IS_ACTIVATION == 1) {
//                    ToastUtils.show(this, getString(R.string.account_no_activation))
//                } else {
//                    startActivity(Intent(this, SecuritySetActivity::class.java))
//                }
//            }
//            //推荐下载
//            R.id.recommend_download_ll -> startActivity(Intent(this, RecommendActivity::class.java))
//            //获取剪贴板管理器：
//            R.id.copy_tv -> {
//                val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
//                val mClipData = ClipData.newPlainText("Label", address_tv.text.toString())
//                cm.setPrimaryClip(mClipData)
//                showToast("复制成功")
//            }
//            R.id.backup_wallet_ll -> {
//                showInputPwdDialog()
//            }
//        }
//    }
//
//    private fun exit() {
//        App.context.logout()
//    }
//
//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
//            IS_ACTIVATION = 2
//            userViewModel.activityTransferList()
//        }
//    }
//
//    private fun showInputPwdDialog() {
//        val contentView = layoutInflater.inflate(R.layout.dialog_input_wallet_pwd, null, false)
//        pwdDialog = DialogUtil.show(this, contentView)
//        pwdDialog?.setOnDismissListener {
//            pwdDialog = null
//        }
//        pwdDialog?.setCancelable(true)
//        pwdDialog?.show()
//        contentView.findViewById<ImageView>(R.id.close_iv).setOnClickListener {
//            pwdDialog?.dismiss()
//        }
//
//        contentView.findViewById<TextView>(R.id.check_pwd_tv).setOnClickListener {
//            val pwd = contentView.findViewById<EditText>(R.id.pwd_et).text.toString().trim()
//            if (TextUtils.isEmpty(pwd)) {
//                showToast("密码不能为空")
//            } else {
//                //服务端验证
//                walletViewModel.checkWalletSecurityPwd(pwd)
//                pwdDialog?.dismiss()
//                showProgress(true)
//            }
//        }
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onWalletInfoEvent(e: WalletInfoEvent) {
//        showProgress(false)
//        val info = NetDataManager.wallletInfo ?: return;
//        wallet_name_tv.text = info.walletName
//        address_tv.text = "${info.utiAddress}"
//        copy_tv.visibility = View.VISIBLE
//        if (IS_ACTIVATION == 1) {
//            super_tv.text = ""
//        } else {
//            if (info.walletLevel == 0) {
//                super_tv.text = "矿工"
//            } else {
//                super_tv.text = getString(R.string.super_node)
//            }
//        }
//
//    }
//
//    override fun onDestroy() {
//        super.onDestroy()
//        pwdDialog = null
//    }
}